<template>
  <ElementDialog
    ref="dialog"
    :visible="visible"
    embed
    title="退回"
    vertical-center
    :offset-top="-260"
    width="600px"
    v-on="$listeners">
    <FormHolder ref="form" :model="entity" label-width="0">
      <FormItem block required prop="nodeId" label="环节" prefix-pick hide-label>
        <!-- 环节信息 -->
        <fieldset style="padding: 10px; border: 1px solid #ddd; border-radius: 4px">
          <legend style="padding: 0 4px; color: var(--color-primary)">{{ `${options?.length > 1 ? '请选择' : ''}退回环节` }}</legend>
          <ElSelect
            v-model="entity.nodeId"
            :disabled="!options || options.length === 1"
            clearable
            placeholder="请选择"
            style="width: 100%">
            <ElOption v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
          </ElSelect>
          <XInputTag style="margin-top: 6px" disabled label="处理人" :value="entity.users" />
        </fieldset>
      </FormItem>
      <FormItem block required prop="advice" label="退回说明" hide-label>
        <ElInput v-model="entity.advice" type="textarea" :rows="5" placeholder="请输入退回说明" />
      </FormItem>
    </FormHolder>
    <template #footer>
      <ConfirmButton :confirmable="false" loadable type="primary" size="small" @click="reject">确定</ConfirmButton>
      <ElButton plain size="small" @click="() => $refs.dialog.hide()">取消</ElButton>
    </template>
  </ElementDialog>
</template>

<script>
  import { getBackNodes, reject } from '@/api/admin/workitem'

  export default {
    name: 'FlowRejectDialog',
    props: {
      visible: Boolean,
      variables: Object,
      flowContext: Object,
      businessKey: String
    },
    data() {
      return {
        options: [],
        entity: {
          nodeId: '',
          users: [],
          advice: ''
        }
      }
    },
    watch: {
      'entity.nodeId': {
        immediate: true,
        handler(newVal) {
          this.entity.users = []
          const row = this.options.find(item => item.id === newVal)
          this.entity.users = row?.handlers ?? []
        }
      }
    },
    async created() {
      const res = await getBackNodes(this.flowContext.taskId)
      this.options = res.data.data
      this.entity.nodeId = this.options[0].id
    },
    methods: {
      async reject() {
        await this.$refs.form.validate()
        const params = {
          businessKey: this.businessKey,
          variables: this.variables,
          targetNodeId: this.entity.nodeId,
          taskId: this.flowContext.taskId,
          advice: this.entity.advice
        }

        const res = await reject(params)

        this.$emit('success', res)
        this.$refs.dialog.hide()
      }
    }
  }
</script>
